import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';

/**
 * 通用列表页组合式函数
 * @param {Object} options - 配置选项
 * @param {Function} options.fetchListApi - 获取列表数据的API函数
 * @param {Function} options.addApi - 添加数据的API函数
 * @param {Function} options.updateApi - 更新数据的API函数
 * @param {Function} options.deleteApi - 删除数据的API函数
 * @param {Object} options.defaultForm - 默认的表单数据
 * @param {Object} options.defaultQuery - 默认的查询条件
 * @param {Boolean} options.useMultiDelete - 是否使用批量删除功能
 * @param {Function} options.afterFetch - 获取数据后的回调函数
 * @param {Function} options.afterSubmit - 提交表单后的回调函数
 * @param {Function} options.afterDelete - 删除数据后的回调函数
 * @param {Boolean} options.hasPagination - 是否使用分页
 * @returns {Object} - 返回列表页所需的状态和方法
 */
export function useTableList(options) {
  
  const {
    fetchListApi,
    addApi,
    updateApi,
    deleteApi,
    defaultForm = {},
    defaultQuery = {},
    // afterFetch,
    // afterSubmit,
    // afterDelete,
    hasPagination = true,
  } = options;

  // 列表数据
  const dataList = ref([]);
  const loading = ref(false);
  
  // 表单相关
  const formRef = ref(null);
  const formState = reactive({...defaultForm});
  const modalVisible = ref(false);
  const submitLoading = ref(false);
  
  // 分页配置
  const pagination = reactive({
    current: 1,
    pageSize: 5,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['5', '10', '20', '30'],
    showTotal: (total) => `共 ${total} 条`
  });

  // 搜索条件
  const queryParams = reactive({...defaultQuery});
  
  // 行选择相关
  const selectedRowKeys = ref([]);

  // 计算弹窗标题
  const modalTitle = computed(() => {
    return formState.id ? '编辑' : '新增';
  });

  // 加载列表数据
  const loadList = async (page = pagination.current, pageSize = pagination.pageSize) => {
    if (!fetchListApi) return;
    
    loading.value = true;
    try {
      const params = hasPagination 
        ? { page, pageSize, ...queryParams } 
        : { ...queryParams };
      
      const res = await fetchListApi(params);
      
      if (res.code === 200) {
        if (hasPagination && res.data.list) {
          dataList.value = res.data.list;
          pagination.total = res.data.total || 0;
          pagination.current = page;
          pagination.pageSize = pageSize;
        } else {
          dataList.value = res.data;
        }
        
        // 调用自定义获取数据后的回调
        // afterFetch && afterFetch(res.data);
      } else {
        message.error(res.message || '获取列表失败');
      }
    } catch (error) {
      console.error('加载列表数据出错:', error);
    } finally {
      loading.value = false;
    }
  };

  // 搜索处理
  const handleSearch = (values) => {
    Object.assign(queryParams, values);
    if (hasPagination) {
      pagination.current = 1;
    }
    loadList(1, pagination.pageSize);
  };
  const handleSearch1 = (values) => {
    Object.assign(queryParams, values);
    if (hasPagination) {
      pagination.current = 1;
    }
    loadList(1, pagination.pageSize);
  };

  // 重置搜索
  const resetSearch = () => {
    Object.keys(queryParams).forEach(key => {
      queryParams[key] = undefined;
    });
    
    if (hasPagination) {
      pagination.current = 1;
    }
    loadList(1, pagination.pageSize);
  };

  // 表格变化事件处理
  const tableChange = ({ pagination: tablePagination, filters, sorter }) => {
    if (hasPagination) {
      loadList(tablePagination.current, tablePagination.pageSize);
    }
  };
  
  // 新增
  const handleAdd = () => {
    resetForm();
    modalVisible.value = true;
  };

  // 编辑
  const handleEdit = (record) => {
    resetForm();
    Object.assign(formState, record);
    modalVisible.value = true;
  };

  // 删除
  const handleDelete = async (record) => {
    if (!deleteApi) return;
    
    try {
      const res = await deleteApi({id:record.id});
      if (res.code === 200) {
        message.success('删除成功');
        await loadList();
        
        // 调用自定义删除后的回调
        // afterDelete && afterDelete();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除数据出错:', error);
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async (keys) => {
    if (!deleteApi || !keys.length) return;
    
    try {
      // 这里可以根据实际API调整
      const promises = keys.map(id => deleteApi(id));
      await Promise.all(promises);
      message.success('批量删除成功');
      await loadList();
      selectedRowKeys.value = [];
      
      // 调用自定义删除后的回调
      // afterDelete && afterDelete();
    } catch (error) {
      console.error('批量删除数据出错:', error);
      message.error('批量删除失败');
    }
  };

  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields();
    Object.assign(formState, {...defaultForm});
    modalVisible.value = false;
  };

  // 操作按钮点击
  const handleAction = (action, selectedKeys) => {
    if (action.handler) {
      action.handler(selectedKeys);
    }
  };

  // 行选择配置
  const rowSelection = computed(() => ({
    selectedRowKeys: selectedRowKeys.value,
    onChange: keys => selectedRowKeys.value = keys,
    fixed: true
  }));

  // 表单提交处理
  const handleFormSubmit = async (formData, form = formRef.value) => {
    let submitFormData = formData
    if (!addApi || !updateApi) return;
    
    // 如果提供了表单引用，先进行表单校验
    if (form) {
      try {
        await form.validate();
        submitFormData = formState
      } catch (error) {
        console.error('表单校验失败:', error);
        return;
      }
    }
    
    submitLoading.value = true;
    try {
      let res;
      if (submitFormData.id) {
        // 更新
        res = await updateApi(submitFormData);
      } else {
        // 新增
        res = await addApi(submitFormData);
      }
      
      if (res.code === 200) {
        message.success(res.message || '操作成功');
        modalVisible.value = false;
        await loadList();
        
        // 调用自定义提交后的回调
        // afterSubmit && afterSubmit(res.data);
        return res;
      } else {
        message.error(res.message || '操作失败');
      }
    } catch (error) {
      console.error('提交表单出错:', error);
      message.error('操作失败');
    } finally {
      submitLoading.value = false;
    }
  };

  // 初始加载数据
  onMounted(() => {
    loadList();
  });

  return {
    // 数据
    dataList,
    loading,
    formState,
    formRef,
    queryParams,
    pagination,
    modalVisible,
    submitLoading,
    modalTitle,
    selectedRowKeys,
    rowSelection,
    
    // 方法
    loadList,
    handleSearch,
    handleSearch1,
    resetSearch,
    tableChange,
    handleAdd,
    handleEdit,
    handleDelete,
    handleBatchDelete,
    resetForm,
    handleAction,
    handleFormSubmit
  };
}
